<?php

/*
 * CopyRight  : (C)2012-2099 HaoTeam Inc.
 * Document   : Callback.php
 * Created on : 2023-3-27 16:10:13
 * Author     : Tiger <1192851302@qq.com>
 * Description: This is NOT a freeware, use is subject to license terms.
 *              这即使是一个免费软件,使用时也请遵守许可证条款,得到当时人书面许可.
 *              未经书面许可,不得翻版,翻版必究;版权归属 HaoTeam Inc;
 */

namespace app\api\controller\tiktok;

use app\Request;
use haoteam\service\UtilService;
use app\models\Payment;
use app\models\Refunds;
use haoteam\service\TikTokService;

/**
 * 
 * Class Callback
 * Tiger <1192851302@qq.com> 2023-3-27 16:10:13
 */
class Callback {

    /**
     * 小程序支付回调
     * @author Tiger <1192851302@qq.com>
     * @param Request $request
     */
    public function payment(Request $request) {
        \think\facade\Log::debug('字节支付回调参数 | '. json_encode($request->post()));
        [$timestamp, $nonce, $msg, $type, $msg_signature] = UtilService::postMore([
                    'timestamp', 'nonce', 'msg', 'type', 'msg_signature'], $request, true);
        try {
            $message = TikTokService::instance()->notify($timestamp, $nonce, $msg, $msg_signature);
        } catch (\Exception $exc) {
            return \think\Response::create(['err_no' => 1, 'err_tips' => $exc->getMessage()], 'json');
        }
        if (in_array($type, ['payment']) == false) {
            return \think\Response::create(['err_no' => 1, 'err_tips' => '系统错误'], 'json');
        }
        $payment = Payment::where('out_trade_no', $message['cp_orderno'])->where('status', 0)->field([
                    'id', 'join_id', 'attach', 'callback', 'callback_status', 'out_trade_no'
                ])->find();
        if (empty($payment)) {
            return \think\Response::create(['err_no' => 0, 'err_tips' => 'success'], 'json');
        }
        try {
            //更新支付表
            Payment::update(['transaction_id' => $message['channel_no'], 'status' => 1, 'pay_time' => date('Y-m-d H:i:s')], ['id' => $payment['id']]);
            //通知应用
            call_user_func_array(array("{$payment['callback']}", "paySuccess"), compact('message', 'payment'));
        } catch (\Exception $exc) {
            return \think\Response::create(['err_no' => 1, 'err_tips' => $exc->getMessage()], 'json');
        }
        return \think\Response::create(['err_no' => 0, 'err_tips' => 'success'], 'json');
    }

}
